package com.weiyi.weiman.interceptor;

import com.weiyi.weiman.utils.IPUtils;
import com.weiyi.weiman.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @Author zhang
 * @Date 2021/5/2 上午1:25
 * @Description ip黑名单拦截器
 * @Version 1.0
 **/
@Slf4j
public class IpBlackInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtils redisUtils;

    @Value("${weiman.ip-black-pre}")
    private String IP_BLACK_PRE;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        String ipAddr = IPUtils.getIpAddr(request);
        if (!Objects.isNull(redisUtils.get(IP_BLACK_PRE + ipAddr))
                && Integer.parseInt(redisUtils.get(IP_BLACK_PRE + ipAddr)+"") > 5) {
            log.info("请求ip:" + ipAddr + "在ip黑名单中，进行拦截");
            return false;
        }
        log.info("请求ip:" + ipAddr + "不在ip黑名单中，放行");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
